package api

import (
	"coroutine/api_client/handler/request"
	pb "coroutine/api_client/proto"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
)

func AddOrder(c *gin.Context) {
	var req request.AddOrderReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	client := pb.NewUserClient(conn)

	order, _ := client.AddOrder(c, &pb.AddOrderReq{
		Uid:     uint64(c.GetUint("userId")),
		TId:     req.TId,
		ONum:    req.ONum,
		OStatus: req.OStatus,
	})
	c.JSON(200, order)
}

func QueryOrder(c *gin.Context) {
	var req request.QueryOrderReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	client := pb.NewUserClient(conn)

	order, _ := client.QueryOrder(c, &pb.QueryOrderReq{
		Uid:               uint64(c.GetUint("userId")),
		TicketTrainNumber: req.TicketTrainNumber,
	})
	c.JSON(200, order)
}

func QueryOrderType(c *gin.Context) {
	var req request.QueryOrderTypeReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	client := pb.NewUserClient(conn)

	order, _ := client.QueryOrderType(c, &pb.QueryOrderTypeReq{
		Uid:        uint64(c.GetUint("userId")),
		TicketType: req.TicketType,
	})
	c.JSON(200, order)
}

func QueryTickerId(c *gin.Context) {
	var req request.QueryTickerIdReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	client := pb.NewUserClient(conn)

	order, _ := client.QueryOrderId(c, &pb.QueryOrderIdReq{
		Uid: uint64(c.GetUint("userId")),
		OId: req.Id,
	})
	c.JSON(200, order)
}
